package com.atguigu.gmall.item.rpc;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.item.comp.RedisDistLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/api/inner/rpc/item")
public class HelloTestController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedisDistLock redisDistLock;
    @Autowired
    RedissonClient redissonClient;
    @GetMapping("/incr")
    public Result incr() throws InterruptedException {
        //ReentrantLock lock = new ReentrantLock();
//        lock.lock();
        //String token = redisDistLock.lock();
        RLock lock = redissonClient.getLock("lock");
        //boolean b1 = lock.tryLock();//尝试加锁 不等 默认30s过期
        //boolean b1 = lock.tryLock(10, TimeUnit.SECONDS);//10s不断尝试加锁 只等有限时间
        boolean b = lock.tryLock(10, 15, TimeUnit.SECONDS);//10s内不断尝试加锁 加锁后15s释放
        if (b){
            try {
                lock.lock();
                //读取到值
                String abc = redisTemplate.opsForValue().get("abc");
                //修改
                int i = Integer.parseInt(abc) + 1;
                //保存到redis
                redisTemplate.opsForValue().set("abc",i+"");
            }finally {
                lock.unlock();
                //lock.unlock();
                //redisDistLock.unLock(token);
            }
        }
        return Result.ok();
    }
}
